/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.fatecpg.songs.intranet.managedbeans;

import br.com.fatecpg.songs.crud.facade.RegisterFacade;
import br.com.fatecpg.songs.dao.util.DAOException;
import br.com.fatecpg.songs.entity.Musician;
import br.com.fatecpg.songs.util.FacesContextUtil;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.hibernate.exception.ConstraintViolationException;

/**
 *
 * @author Marcos
 */
@ManagedBean
@ViewScoped
public class MusicianManagedBean implements RegisterManagedBean<Musician>{      
    private int viewState;    
    private RegisterFacade<Musician> facade = new RegisterFacade<Musician>(Musician.class);     
    private Musician musician;  
    private List<Musician> list;

    public MusicianManagedBean() throws DAOException{
        musician = new Musician();          
        list = facade.list();
        this.viewState = LIST_STATE;
    }
                                  
    @Override
    public void openNew() {
        this.musician = new Musician();        
        this.viewState = REGISTER_STATE;
    }

    @Override
    public void openToUpdate() throws DAOException {                
        this.musician = facade.load();
        this.viewState = REGISTER_STATE;
    }

    @Override
    public void register() throws DAOException{    
        facade.setUpdateInfo(musician);
        facade.register(musician);        
        list = facade.list();
        viewState = LIST_STATE;        
    }

    @Override
    public void delete() throws DAOException { 
         try{
            facade.delete();
            list = facade.list();
            this.viewState = LIST_STATE;            
        }catch(ConstraintViolationException ex){
             FacesContextUtil.addMessage("Existem composições deste músico e/ou artistas em que este é participante. Para deletá-lo, é necessário deletar as composições e os artistas.");
        }        
    }

    @Override
    public List<Musician> getList() {
        return list;
    }

    @Override
    public void cancel() {
        this.musician = new Musician();
        this.viewState = LIST_STATE;        
    }    
    
    public Musician getMusician() {
        return musician;
    }
    
    public void setMusician(Musician musician) {
        this.musician = musician;
    }
    
    public int getViewState() {
        return viewState;
    }    

    public void setViewState(int viewState) {
        this.viewState = viewState;
    }   
}
